package com.ankiang.treeprint.fragment.components;

import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.ankiang.treeprint.R;
import com.ankiang.treeprint.base.BaseFragment;
import com.ankiang.treeprint.fragment.util.TRPages;
import com.ankiang.treeprint.fragment.util.TRUtils;
import com.ankiang.treeprint.lib.Group;
import com.ankiang.treeprint.lib.TRDataManager;
import com.ankiang.treeprint.lib.annotation.Widget;
import com.ankiang.treeprint.manager.QDDataManager;
import com.ankiang.treeprint.model.LOG;
import com.ankiang.treeprint.model.TRItemNode;
import com.ankiang.treeprint.model.TRItemTree;
import com.ankiang.treeprint.view.TRConfig;
import com.ankiang.treeprint.view.TRLayout;
import com.ankiang.treeprint.view.TRListener;
import com.qmuiteam.qmui.util.QMUIViewHelper;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView;
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListView;

import org.devio.takephoto.app.TakePhotoFragment;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * {@link QMUIGroupListView} 的使用示例。
 * Created by Kayo on 2016/11/21.
 */


@Widget(group = Group.Seekpic, widgetClass = TRTimeFlyFragment.class, iconRes = R.drawable.ic_icon_help)
public class TRAddItemFragment extends BaseFragment {
    // 操作状态
    public static final int EDIT = 1;
    public static final int ADD = 2;

    public static String KEY_TAG = "KEY_TAG";
    public static String KEY_DATA = "KEY_DATA";
    public static String KEY_OTHER_DATA = "KEY_OTHER_DATA";


    static final int TAG_DETAILS = -2;
    static final int TAG_NEW = -1;
    static final int TAG_FATHER = 11;
    static final int TAG_MOTHER = 1;
    static final int TAG_ELER_BROTHER = 2;
    static final int TAG_BROTHER = 3;
    static final int TAG_ELDER_SISTER = 4;
    static final int TAG_SISTER = 5;
    static final int TAG_WIFE = 6;
    static final int TAG_HUSBAND = 7;
    static final int TAG_SON = 8;
    static final int TAG_DAUGHTER = 9;
    static final int TAG_MARRY = 10;


    @BindView(R.id.topbar)
    QMUITopBarLayout mTopBar;

    @BindView(R.id.groupListView)
    QMUIGroupListView mGroupListView;

    // 称呼
    @BindView(R.id.item_callname)
    TextView itemCallNameTextView;

    // 姓名和昵称
    @BindView(R.id.item_name)
    TextView itemNameTextView;
    // 姓名和昵称
    @BindView(R.id.item_nickname)
    TextView itemNicknameTextView;

    @BindView(R.id.item_id)
    TextView itemIdTextView;

    @BindView(R.id.item_sex)
    ImageButton itemSexImageButton;


    @BindView(R.id.item_image)
    ImageButton itemImageButton;

    @BindView(R.id.item_remark)
    TextView itemRemarkTextView;


    @BindView(R.id.container)
    View container;

    @BindView(R.id.summary_tree_grid_layout)
    TRLayout summaryTRLayout;


    QMUICommonListItemView fatherItem;
    QMUICommonListItemView motherItem;
    QMUICommonListItemView bornDateMoonItem;
    QMUICommonListItemView bornDateSunItem;
    QMUICommonListItemView orderItem;

    private QDDataManager.QDItemDescription mQDItemDescription;


    // 右上角列表
//    private QMUIListPopup mListPopup;
//    private QMUIAlphaImageButton mRightButton;


    // 局部树，包含父母、兄弟、子女
    TRItemTree summaryItemTree;


    // 保存数据
//    private int itemId;
    private TRItemTree itemTree;

    TRItemNode data;
    TRItemNode otherData;
    int tag;


    // 配置
    private TRConfig conf;
    private int mOp = ADD;
    private TRListener afterOperationListener;


    TRDataManager dataManager;


    @Override
    protected View onCreateView() {
        View root = LayoutInflater.from(getActivity()).inflate(R.layout.tr_fragment_add_item, null);
        ButterKnife.bind(this, root);

        conf = TRConfig.getInstance();
        dataManager = TRDataManager.getInstance(getContext());


        mQDItemDescription = QDDataManager.getInstance(getContext()).getDescription(this.getClass());

        Bundle bundle = getArguments();
        if (bundle != null) {
            tag = bundle.getInt(KEY_TAG);
            data = (TRItemNode) bundle.getSerializable(KEY_DATA);
            if (data != null) {
                data = data.clone();
            } else {
                data = new TRItemNode(); // 防止崩溃的做法
            }
            otherData = (TRItemNode) bundle.getSerializable(KEY_OTHER_DATA);
            if (otherData != null) {
                otherData = otherData.clone();
            }
        } else {
            tag = 0;
            data = new TRItemNode();
            otherData = new TRItemNode();
        }

        summaryTRLayout.setItemLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                // 这里不能长按
                return true;
            }
        });


        initTopBar();

        initGroupListView();

        initListener();
        if (mOp == ADD) {
            showEditCallnameDialog();
        }
        return root;
    }


    private void initListener() {

        if (itemSexImageButton != null) {
            itemSexImageButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showSexChoiceDialog();
                }
            });
        }

        if (itemNicknameTextView != null) {
            itemNicknameTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showEditNicknameDialog();
                }
            });
        }
        if (itemNameTextView != null) {
            itemNameTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showEditNameDialog();
                }
            });
        }
        if (fatherItem != null) {
            fatherItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showEditFatherDialog();
                }
            });
        }
        if (motherItem != null) {
            motherItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showEditMotherDialog();
                }
            });
        }
        if (orderItem != null) {
            orderItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showEditOrderDialog();
                }
            });
        }
        if (bornDateMoonItem != null) {
            bornDateMoonItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showEditBornDateMoonDialog();
                }
            });
        }
        if (bornDateSunItem != null) {
            bornDateSunItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showEditBornDateSunDialog();
                }
            });
        }
        if (itemRemarkTextView != null) {
            itemRemarkTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showEditRemarkDialog();
                }
            });
        }
        if (itemCallNameTextView != null) {
            itemCallNameTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showEditCallnameDialog();
                }
            });
        }
        if (itemImageButton != null) {
            itemImageButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showEditImageDialog();
                }
            });
        }

    }

    /**
     * 保存数据并退出当前页面
     */
    private void done() {
        int id = 0;
        if (mOp == EDIT) {
            id = data.getId();
        } else if (mOp == ADD && itemTree != null) {
            data.setId(data.getId());
        }
        if (itemTree != null) {
            data.refreshUpdatetime();
            itemTree.put(data.getId(), data);

            if (otherData != null && otherData.getId() != -1) {
                // 自动生成结合名称
                if (otherData.getSex() == TRItemNode.Sex.COUPLE) {
                    itemTree.refreshCoupleName(otherData);
                }
                otherData.refreshUpdatetime();
                itemTree.put(otherData.getId(), otherData);
            }
        }
        if (afterOperationListener != null) {
            afterOperationListener.afterOperation(id);
        }
        dataManager.setData(itemTree.getGroupId(), itemTree);
        dataManager.save(); //保存结果
        popBackStack();
    }

    private void initTopBar() {
        mTopBar.addRightTextButton(R.string.done, QMUIViewHelper.generateViewId())
                .setOnClickListener(v -> {
                    done();
                });

        mTopBar.setOnLongClickListener(v -> {
            TRShowTextFragment fragment = new TRShowTextFragment();
            fragment.setOp(TRShowTextFragment.OP_SHOW_ITEM);
            String content = data.toJSONString();
            fragment.setContent(content);
            fragment.setId(data.getId());
            startFragment(fragment);
            return true;
        });

        if (mOp == EDIT) {
            // 取消
            mTopBar.addLeftBackImageButton().setOnClickListener(v -> {
                cancel();
            });
//            // 删除
//            mTopBar.addLeftTextButton("删除", QMUIViewHelper.generateViewId())
//                    .setOnClickListener(v -> {
//                        showMessageNegativeDeleteDialog();
//                    });


            mTopBar.setTitle(R.string.details);
        } else if (mOp == ADD) {
            mTopBar.addLeftTextButton(R.string.cancel, QMUIViewHelper.generateViewId())
                    .setOnClickListener(v -> {
                        popBackStack();
                    });
            mTopBar.setTitle(R.string.details_op_add);
        }


    }


    private void initGroupListView() {
        if (this.itemTree == null) {
            return;
        }

        String father = TRItemNode.getNone();
        String mother = TRItemNode.getNone();
        if (mOp == ADD) {
//            LOG.jLogi("ItemId=%d", data.getId());
            // 取这个数据
            if (data == null) {
                data = new TRItemNode();
            } else {
                if (itemTree.hasFather(data)) {
                    father = itemTree.get(data.getFid()).getCallname();
                }
                if (itemTree.hasMother(data)) {
                    mother = itemTree.get(data.getMid()).getCallname();
                }
            }
            mTopBar.setTitle(V(R.string.details_op_add));
        } else {
            mTopBar.setTitle(V(R.string.details));
            container.setVisibility(View.VISIBLE);
        }


        if (data == null || data.isEmpty()) {
            LOG.jLogi("itemTree[itemId]=null");
        }

        int id = data.getId();
        String nickname = data.getNickname();
        String name = data.getName();
        int fid = data.getFid();
        int mid = data.getMid();
        String remark = data.getRemark();
        String imgPath = data.getImage();
        String bornDateSun = data.getBornDateSun();
        String bornDateMoon = data.getBornDateMoon();
        char sex = data.getSex();
        int order = data.getOrder();
        String callname = data.getCallname();


        // todo 设置用户的选中状态
        data.setState(TRItemNode.Status.FOCUSED);


        String summaryText = "";

        // 只有编辑才需要展示
        if (mOp == EDIT) {
            // todo 取父母、子女、兄弟
            summaryItemTree = new TRItemTree();
            summaryItemTree.addItem(data); // 自己


            if (itemTree.hasFather(data)) {
                TRItemNode itemFather = itemTree.get(fid);
                father = itemFather.getCallname();
                summaryItemTree.addItem(itemFather); // 父
            }
            if (itemTree.hasMother(data)) {
                TRItemNode itemMother = itemTree.get(mid);
                mother = itemMother.getCallname();
                summaryItemTree.addItem(itemMother); // 母
            }


            // todo 子女数量
            int brotherCount = 0;
            int sonCount = 0;
            int offspringCount = 0;

            Set<Integer> offspringSet = new HashSet<>();
            Set<Integer> sonSet = itemTree.getChildren(data.getId());
            Set<Integer> brotherSet = new HashSet<>();


            // 添加若干代子辈
            int generationCount = 3;
            Set<Integer> handleSet = itemTree.getChildren(data.getId());
            for (int i = 0; i < generationCount && !handleSet.isEmpty(); i++) {
                Set<Integer> tmpSet = new HashSet<>();
                Iterator<Integer> siter = handleSet.iterator();
                while (siter.hasNext()) {
                    int sid = siter.next();
                    if (summaryItemTree.containsKey(sid)) {
                        continue;
                    }
                    TRItemNode item = itemTree.get(sid);
                    summaryItemTree.put(sid, item);
                    tmpSet.addAll(itemTree.getChildren(sid));
                }
                handleSet = tmpSet;
            }

            // 把所有的节点的父母都加进来
            Iterator<TRItemNode> iterItem = summaryItemTree.values().iterator();
            TRItemTree tmpTree = new TRItemTree();
            while (iterItem.hasNext()) {
                TRItemNode tmp = iterItem.next();
                if (itemTree.hasMother(tmp)) {
                    int tid = tmp.getMid();
                    TRItemNode tmpItem = itemTree.getMother(tmp);
                    tmpTree.put(tid, tmpItem);
                }
                if (itemTree.hasFather(tmp)) {
                    int tid = tmp.getFid();
                    TRItemNode tmpItem = itemTree.getFather(tmp);
                    tmpTree.put(tid, tmpItem);
                }
            }
            summaryItemTree.putAll(tmpTree);


            // TODO 子辈数量不对
            Iterator iter = itemTree.entrySet().iterator();
            while (iter.hasNext()) {
                HashMap.Entry entry = (HashMap.Entry) iter.next();
                TRItemNode item = (TRItemNode) entry.getValue();


                // 同辈
                // 父母的ID与自己相同
                if (itemTree.hasFather(data) && (item.getFid() == fid || item.getMid() == fid)) {
                    summaryItemTree.addItem(item);
                    brotherSet.add(item.getId());
                }

                if (itemTree.hasMother(data) && (item.getFid() == mid || item.getMid() == mid)) {
                    summaryItemTree.addItem(item);
                    brotherSet.add(item.getId());
                }

                // 子辈，子辈的父母（即自己的对象）
                if (item.getMid() == id || item.getFid() == id) {
                    summaryItemTree.addItem(item);
                    if (itemTree.hasFather(item)) {
                        summaryItemTree.addItem(itemTree.get(item.getFid()));
                    }
                    if (itemTree.hasMother(item)) {
                        summaryItemTree.addItem(itemTree.get(item.getMid()));
                    }
                    offspringSet.add(item.getId());
                }

            }
            offspringCount = offspringSet.size();
            brotherCount = brotherSet.size();
            sonCount = sonSet.size();
            summaryText = String.format(V(R.string.details_summary_format), brotherCount, sonCount, offspringCount);

            // 局部树
            summaryTRLayout.setItemTree(summaryItemTree);
            summaryTRLayout.setFullPercent();
            // 初始化树
            summaryTRLayout.initWithTree();
            summaryTRLayout.setSelected(data.getId());

        }


        itemNameTextView.setText(String.format(V(R.string.details_name_format), name, nickname));
        itemCallNameTextView.setText(callname);

        fatherItem = mGroupListView.createItemView(V(R.string.details_father));
        fatherItem.setOrientation(QMUICommonListItemView.HORIZONTAL);
        fatherItem.setDetailText(father);

        motherItem = mGroupListView.createItemView(V(R.string.details_mother));
        motherItem.setOrientation(QMUICommonListItemView.HORIZONTAL);
        motherItem.setDetailText(mother);

        bornDateMoonItem = mGroupListView.createItemView(V(R.string.details_bornDateMoon));
        bornDateMoonItem.setOrientation(QMUICommonListItemView.HORIZONTAL);
        bornDateMoonItem.setDetailText(bornDateMoon);

        bornDateSunItem = mGroupListView.createItemView(V(R.string.details_bornDateSun));
        bornDateSunItem.setOrientation(QMUICommonListItemView.HORIZONTAL);
        bornDateSunItem.setDetailText(bornDateSun);

        orderItem = mGroupListView.createItemView(V(R.string.details_order));
        orderItem.setOrientation(QMUICommonListItemView.HORIZONTAL);
        orderItem.setDetailText(String.valueOf(order));

        itemCallNameTextView.setText(callname);
        itemIdTextView.setText(String.format(V(R.string.details_id_format), id));

        // 性别
        itemSexImageButton.setImageResource(conf.getSexImgId(sex));

        itemRemarkTextView.setText(remark);

        itemNicknameTextView.setText(nickname);
        itemNameTextView.setText(name);


        int imgid = conf.getImgId(sex);

        Drawable imgDrawable = null;
        if (null != imgPath && !imgPath.equals("")) {
            imgDrawable = Drawable.createFromPath(imgPath);
        }
        if (imgDrawable == null) { // 如果上一部没有创建成功，也会调用这里
            imgDrawable = getResources().getDrawable(imgid);
        }

        itemImageButton.setImageDrawable(imgDrawable);


        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v instanceof QMUICommonListItemView) {
                    CharSequence text = ((QMUICommonListItemView) v).getText();
                    Toast.makeText(getActivity(), text + " is Clicked", Toast.LENGTH_SHORT).show();
                }
            }
        };


        QMUIGroupListView.newSection(getContext())
                .setTitle(V(R.string.details))
                .setDescription(summaryText)
                .addItemView(fatherItem, onClickListener)
                .addItemView(motherItem, onClickListener)
                .addItemView(orderItem, onClickListener)
                .addItemView(bornDateMoonItem, onClickListener)
                .addItemView(bornDateSunItem, onClickListener)
                .addTo(mGroupListView);
    }


    public void setItemTree(TRItemTree itemTree) {
        this.itemTree = itemTree;
    }


    // 取消确认弹窗
    private void showMessageNegativeDialog() {
        new QMUIDialog.MessageDialogBuilder(getActivity())
                .setTitle(V(R.string.cancel))
                .setMessage(V(R.string.add_cancel_confirm_tips))
                .addAction(V(R.string.cancel), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, V(R.string.ok), QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {

                        dialog.dismiss();

                        popBackStack();
                    }
                })
                .create().show();
    }


    private void showSexChoiceDialog() {
        final String[] items = new String[]{
                V(R.string.item_sex_male),
                V(R.string.item_sex_female),
                V(R.string.item_sex_couple),
                V(R.string.item_sex_neuter),
                V(R.string.item_sex_unknown)};
        final char[] sexChars = new char[]{
                'M', 'F', '0', '1', '?'
        };
        int checkedIndex = 4;
        for (int i = 0; i < sexChars.length; i++) {
            if (sexChars[i] == data.getSex()) {
                checkedIndex = i;
                break;
            }
        }

        new QMUIDialog.CheckableDialogBuilder(getActivity())
                .setCheckedIndex(checkedIndex)
                .addItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getActivity(), "你选择了 " + items[which], Toast.LENGTH_SHORT).show();
                        char ch = sexChars[which];
                        char oldCh = data.getSex();
                        data.setSex(ch);
                        itemSexImageButton.setImageResource(conf.getSexImgId(ch));
                        itemImageButton.setImageResource(conf.getImgId(ch));
                        dialog.dismiss();
                    }
                })
                .create().show();
    }


    private void showEditNameDialog() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(getActivity());
        String s = data.getName();
        if (TRItemNode.getNone().equals(s)) {
            s = "";
        }
        builder.setTitle(V(R.string.additem_name))
                .setPlaceholder(V(R.string.additem_enter_content_tips))
                .setInputType(InputType.TYPE_CLASS_TEXT)
                .setDefaultText(s)
                .addAction(V(R.string.cancel), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(V(R.string.ok), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        CharSequence text = builder.getEditText().getText();
                        if (text != null && text.length() > 0) {
                            data.setName(text.toString());
                            itemNameTextView.setText(text);
                            data.refreshUpdatetime();
                            dialog.dismiss();
                        } else {
                            Toast.makeText(getActivity(), V(R.string.additem_enter_content_tips), Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .create().show();
    }

    private void showEditNicknameDialog() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(getActivity());
        String s = data.getNickname();
        if (TRItemNode.getNone().equals(s)) {
            s = "";
        }
        builder.setTitle(V(R.string.additem_nickname))
                .setPlaceholder(V(R.string.additem_enter_content_tips))
                .setInputType(InputType.TYPE_CLASS_TEXT)
                .setDefaultText(s)
                .addAction(V(R.string.cancel), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(V(R.string.ok), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        CharSequence text = builder.getEditText().getText();
                        if (text != null && text.length() > 0) {
                            data.setNickname(text.toString());
                            itemNicknameTextView.setText(text);
                            data.refreshUpdatetime();
                            dialog.dismiss();
                        } else {
                            Toast.makeText(getActivity(), V(R.string.additem_enter_content_tips), Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .create().show();
    }

    private void showEditRemarkDialog() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(getActivity());
        String s = data.getRemark();
        if (TRItemNode.getNone().equals(s)) {
            s = "";
        }
        builder.setTitle(V(R.string.additem_remark))
                .setPlaceholder(V(R.string.additem_enter_content_tips))
                .setInputType(InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE)
                .setDefaultText(s)
                .addAction(V(R.string.cancel), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(V(R.string.ok), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        CharSequence text = builder.getEditText().getText();
                        if (text != null && text.length() > 0) {
                            data.setRemark(text.toString());
                            itemRemarkTextView.setText(text);
                            data.refreshUpdatetime();
                            dialog.dismiss();
                        } else {
                            Toast.makeText(getActivity(), V(R.string.additem_enter_content_tips), Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .create().show();
    }

    private void showEditCallnameDialog() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(getActivity());

        String callName = data.getCallname();
        if (TRItemNode.getNone().equals(callName)) {
            callName = "";
        }
        builder.setTitle(V(R.string.additem_callname))
                .setPlaceholder(V(R.string.additem_enter_content_tips))
                .setInputType(InputType.TYPE_CLASS_TEXT)
                .setDefaultText(callName)
                .addAction(V(R.string.cancel), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(V(R.string.ok), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        CharSequence text = builder.getEditText().getText();
                        if (text != null && text.length() > 0) {
                            data.setCallname(text.toString());
                            itemCallNameTextView.setText(text);
                            data.refreshUpdatetime();
                            dialog.dismiss();
                        } else {
                            Toast.makeText(getActivity(), V(R.string.additem_enter_content_tips), Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .create().show();
    }

    private void showEditBornDateMoonDialog() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(getActivity());
        String s = data.getPureBornDateMoon();
        if (TRItemNode.getNone().equals(s)) {
            s = "";
        }
        builder.setTitle(V(R.string.additem_borndatemoon))
                .setPlaceholder(V(R.string.additem_enter_content_tips))
                .setInputType(InputType.TYPE_CLASS_DATETIME)
                .setDefaultText(s)
                .setPlaceholder(R.string.details_date_example)
                .addAction(V(R.string.cancel), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(V(R.string.ok), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        Editable text = builder.getEditText().getText();
                        if (text != null && text.length() > 0) {
                            if (!TRUtils.isRightTimeFormat(text.toString())) {
                                Toast.makeText(getActivity(), V(R.string.additem_wrong_date_format_tips),
                                        Toast.LENGTH_SHORT).show();
                                return;
                            }
                            data.setBornDateMoon(text.toString());
                            bornDateMoonItem.setDetailText(data.getBornDateMoon());
                            data.refreshUpdatetime();
                            dialog.dismiss();
                        } else {
                            Toast.makeText(getActivity(), V(R.string.additem_enter_content_tips), Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .create().show();
    }

    private void showEditBornDateSunDialog() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(getActivity());
        String s = data.getBornDateSun();
        if (TRItemNode.getNone().equals(s)) {
            s = "";
        }
        builder.setTitle(V(R.string.additem_borndatesun))
                .setPlaceholder(V(R.string.additem_enter_content_tips))
                .setInputType(InputType.TYPE_CLASS_DATETIME)
                .setDefaultText(s)
                .setPlaceholder(R.string.details_date_example)
                .addAction(V(R.string.cancel), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(V(R.string.ok), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        CharSequence text = builder.getEditText().getText();
                        if (text != null && text.length() > 0) {
                            if (!TRUtils.isRightTimeFormat(text.toString())) {
                                Toast.makeText(getActivity(), V(R.string.additem_wrong_date_format_tips),
                                        Toast.LENGTH_SHORT).show();
                                return;
                            }
                            data.setBornDateSun(text.toString());
                            bornDateSunItem.setDetailText(data.getBornDateSun());
                            data.refreshUpdatetime();
                            dialog.dismiss();
                        } else {
                            Toast.makeText(getActivity(), V(R.string.additem_enter_content_tips), Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .create().show();
    }

    private void showEditImageDialog() {

        TakePhotoFragment fragment = new TakePhotoFragment();
        fragment.setImageButton(itemImageButton);

        Bundle bundle = new Bundle();
        bundle.putInt(TRAddItemFragment.KEY_TAG, tag);
        bundle.putSerializable(TRAddItemFragment.KEY_DATA, data);
        fragment.setArguments(bundle);

        this.startFragment(fragment);

    }

    private void showEditFatherDialog() {

        TRListener listener = new TRListener() {
            @Override
            public void afterOperation(int id) {
                String tips = null;
                // 如果父母辈相同，则将另一个置0
                if (data != null && id != 0 && data.getMid() == id) {
                    tips = V(R.string.additem_parent_same_tips);
                    Toast.makeText(getContext(), tips, Toast.LENGTH_SHORT).show();
                    data.setMid(0);
                    motherItem.setDetailText(TRItemNode.getNone());
                }
                if (data != null && data.getId() == id) {
                    tips = V(R.string.additem_parent_self_tips);
                    final QMUITipDialog tipDialog;
                    tipDialog = new QMUITipDialog.Builder(getContext())
                            .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
                            .setTipWord(tips)
                            .create();
                    tipDialog.show();
                    mGroupListView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            tipDialog.dismiss();
                        }
                    }, 1500);
                    return;
                }
                TRItemNode item = itemTree.get(id);
                if (item == null) {
                    data.setFid(0);
                    fatherItem.setDetailText(TRItemNode.getNone());
                } else {
                    fatherItem.setDetailText(item.getCallname());
                    data.setFid(id);
                    data.refreshUpdatetime();
                }
            }
        };

        TRSearchItemFragment fragment = new TRSearchItemFragment();
        fragment.setItemTree(itemTree);
        fragment.setSearchCallBack(listener);

        startFragment(fragment);
    }

    private void showEditMotherDialog() {

        TRListener listener = new TRListener() {
            @Override
            public void afterOperation(int id) {

                String tips = null;
                // 如果父母辈相同，则将另一个置0
                if (data != null && id != 0 && data.getFid() == id) {
                    tips = V(R.string.additem_parent_same_tips);
                    Toast.makeText(getContext(), tips, Toast.LENGTH_SHORT).show();
                    data.setFid(0);
                    fatherItem.setDetailText(TRItemNode.getNone());
                }
                if (data != null && data.getId() == id) {
                    final QMUITipDialog tipDialog;
                    tipDialog = new QMUITipDialog.Builder(getContext())
                            .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
                            .setTipWord(V(R.string.additem_parent_self_tips))
                            .create();
                    tipDialog.show();
                    mGroupListView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            tipDialog.dismiss();
                        }
                    }, 1500);
                    return;
                }
                TRItemNode item = itemTree.get(id);

                if (item == null) {
                    motherItem.setDetailText(TRItemNode.getNone());
                    data.setMid(0);
                } else {
                    motherItem.setDetailText(item.getCallname());
                    data.setMid(id);
                    data.refreshUpdatetime();
                }
            }
        };

        TRSearchItemFragment fragment = new TRSearchItemFragment();
        fragment.setItemTree(itemTree);
        fragment.setSearchCallBack(listener);

        startFragment(fragment);
    }

    private void showEditOrderDialog() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(getActivity());
        builder.setTitle(V(R.string.additem_order))
                .setPlaceholder(V(R.string.additem_enter_content_tips))
                .setInputType(InputType.TYPE_CLASS_NUMBER)
//                .setDefaultText(String.valueOf(data.getOrder()))
                .addAction(V(R.string.cancel), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(V(R.string.ok), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        CharSequence text = builder.getEditText().getText();
                        if (text != null && text.length() > 0) {
                            int order = Integer.parseInt(String.valueOf(text));
                            data.setOrder(order);
                            orderItem.setDetailText(text);
                            data.refreshUpdatetime();
                            dialog.dismiss();
                        } else {
                            Toast.makeText(getActivity(), V(R.string.additem_enter_content_tips), Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .create().show();
    }


    /**
     * 取消操作
     */
    private void cancel() {
        // 编辑，且没有变更过，就不用弹窗
        if (mOp == EDIT && itemTree.get(data.getId()).compareTo(data) == 0) {
            popBackStack();
            return;
        } else {
            showMessageNegativeDialog();
        }
    }


    // 删除确认弹窗
    private void showMessageNegativeDeleteDialog() {
        new QMUIDialog.MessageDialogBuilder(getActivity())
                .setTitle(V(R.string.details_op_delete))
                .setMessage(V(R.string.details_op_delete_confirm_tips))
                .addAction(V(R.string.details_op_cancel), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, V(R.string.details_op_delete), QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        if (mOp == EDIT) { // 只有详情才需要删除
                            itemTree.remove(data.getId());
                        }

                        if (afterOperationListener != null) {
                            afterOperationListener.afterOperation(0);
                        }
                        Toast.makeText(getActivity(), V(R.string.details_op_delete_success), Toast.LENGTH_SHORT).show();
                        dialog.dismiss();


                        popBackStack();
                    }
                })
                .create().show();
    }

    public void setAfterOperation(TRListener listener) {
        this.afterOperationListener = listener;
    }

    public void setOp(int op) {
        this.mOp = op;
    }
}
